var page = {
    init: function () {
        $('#unpublish-product').on('click', page.unpublishedProduct);
        $('#trans-product').on('click', page.transTp2CityHunter);
        $('#delete-product').on('click', page.deleteProduct);

        if (CATEGORY == 'city_hunter') {
            page.cityHunterProductEvents();
        } else {
            page.packageProductEvents();
        }
    },
    cityHunterProductEvents: function () {
        page.departPlaceEvents();
        page.similarPruductEvents();
        page.instructionEvents();
        page.productDetailEvents();
        page.subProductEvents();
        // page.mapEvents();
        page.productTabEvents();
        page.languageEvents();
        page.durationEvents();
        page.descriptionEvents();
        page.cityHunterEvents();

        var mapMeet = new page.MapEvents({
            map: page.mapMeet,
            dom: 'map-meet',
            $lat: $('#id_latitude'),
            $lng: $('#id_longitude'),
            marker: page.markerMeet
        });

        var mapAddress = new page.MapEvents({
            map: page.mapAddress,
            dom: 'map-address',
            $lat: $('#id_address_latitude'),
            $lng: $('#id_address_longitude'),
            marker: page.markermapAddress
        });
    },
    packageProductEvents: function () {
        page.departPlaceEvents();
        page.seckillEvents();
        page.relatedTripEvents();
        page.expiredateEvents();
        page.similarPruductEvents();
        page.instructionEvents();
        page.supplierEvents();
        page.tinysiteEvents();
        page.virtualProductEvents();
        page.monthCalendarEvents();
        page.productDetailEvents();
        page.subProductEvents();
        page.descriptionEvents();
        page.scheduleEvents();
    },
    inArray: function (item, arr){
        for(var i = 0; i < arr.length; i++){
            if(arr[i] == item){
                return true;
            }
        }
    },
    categoryEvents: function () {
        $('#id_category2').change(function(){
            if($(this).val() == 'points') {
                $('#departPlacePanel li').each(function(){
                    var e = $(this);
                    if(e.text() == '北京') {
                        e.addClass('selected');
                    } else {
                        e.removeClass('selected');
                    }
                });
                page.saveDepartPlace();
            }
        });
    },
    newWindowFeatures: function () {
        var sh = window.screen.height, sw = window.screen.width, width=800, height=600;
        var left = (sw - width) / 2, top = (sh - height) / 2;
        var features = 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
        features += ',toolbar=no, status=no, menubar=no, channelmode=yes, fullscreen=yes';
        return features;
    },
    addProductInstruction: function (e){
        e.preventDefault();
        window.open(url.PRODUCT_INSTRUCTION_CREATE, '', page.newWindowFeatures);
    },
    move2Instruction: function (detailPk){
        $.post('./movedetail2instruction/', {
            'detail_pk': detailPk
        }, function(data){
            if (data.success) {
                page.appendInstruction(data.pk, data.title);
                page.deleteProductDetail(detailPk);
            } else {
                alert(data.error);
            }
        }, 'json');
    },
    appendInstruction: function (pk, title){
        if ($('#ins-' + pk)[0]) {
            $('#ins-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_instructions').val().split(',');
            ids.push(pk);
            $('#id_instructions').val(ids.join(','));

            var html = '<li id="ins-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/dashboard/tp/product-instruction/' +
                    pk + '/">' + title +
                    '</a><a class="close" onclick="page.deleteInstruction(' + pk +
                    ')">&times;</a></li>';
            $('#instruction-panel').append(html);
        }
    },
    deleteInstruction: function (pk){
        $('#ins-' + pk).remove();
        var content = $('#id_instructions').val();
        $('#id_instructions').val(content.replace(pk, ''));
    },
    instructionEvents: function () {
        $('#add-instruction').on('click', page.addProductInstruction);
        $('#instruction-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#instruction-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_instructions').val(ids.join(','));
            }
        });
        $('#instruction-panel').disableSelection();
    },
    deleteProductDetail: function (pk){
        $('#pd-' + pk).remove();
        var content = $('#id_details').val();
        $('#id_details').val(content.replace(pk, ''));
    },
    deleteProduct: function (){
        $('#form-delete').submit();
    },
    addProductDetail: function (e){
        e.preventDefault();
        window.open(url.PRODUCT_DETAIL_CREATE, '', page.newWindowFeatures);
    },
    appendProductDetail: function (pk, title){
        if ($('#pd-' + pk)[0]) {
            $('#pd-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_details').val().split(',');
            ids.push(pk);
            $('#id_details').val(ids.join(','));

            var html = '<li id="pd-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/dashboard/tp/product-detail/' +
                    pk + '/">' + title + '</a>' +
                    '<a class="close" onclick="page.deleteProductDetail(' + pk +
                    ')">&times;</a>' +
                    '<a href="###" class="label pull-right" onclick="page.move2Instruction(' + pk +
                    ')" style="margin-right:10px;">迁移到亮点推荐</a>' +
                    '</li>';
            $('#description ul').append(html);
        }
    },
    productDetailEvents: function () {
        $('#add-product-detail').on('click', page.addProductDetail);
    },
    descriptionEvents: function () {
        $('#description-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#description-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_details').val(ids.join(','));
            }
        });
        $('#description-panel').disableSelection();
    },
    addProductSchedule: function (e){
        e.preventDefault();
        window.open(url.PRODUCT_SCHEDULE_CREATE, '', page.newWindowFeatures);
    },
    appendSchedule: function (pk, title){
        if ($('#sch-' + pk)[0]) {
            $('#sch-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_schedules').val().split(',');
            ids.push(pk);
            $('#id_schedules').val(ids.join(','));

            var html = '<li id="sch-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/dashboard/tp/product-schedule/' +
                    pk + '/">' + title +
                    '</a><a class="close" onclick="page.deleteSchedule(' + pk +
                    ')">&times;</a></li>';
            $('#schedule-panel').append(html);
        }
    },
    deleteSchedule: function (pk){
        $('#sch-' + pk).remove();
        var content = $('#id_schedules').val();
        $('#id_schedules').val(content.replace(pk, ''));
    },
    scheduleEvents: function () {
        $('#add-product-schedule').on('click', page.addProductSchedule);
        $('#schedule-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#schedule-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_schedules').val(ids.join(','));
            }
        });
        $('#schedule-panel').disableSelection();
    },
    appendTinysite: function (pk, title){
        if ($('#tinysite-' + pk)[0]) {
            $('#tinysite-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_tinysites').val().split(',');
            ids.push(pk);
            $('#id_tinysites').val(ids.join(','));

            var html = '<li id="tinysite-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="">' + title +
                    '</a><a class="close" onclick="page.deleteTinysite(' + pk +
                    ')">&times;</a>' +
                    '<a class="pull-right label" href="###" onclick="page.addParentTinysites(' + pk +
                    ')" style="margin-right:10px;">添加父目的地</a></li>';
            $('#tinysite-panel').append(html);
        }
    },
    deleteTinysite: function (pk){
        $('#tinysite-' + pk).remove();
        var content = $('#id_tinysites').val();
        $('#id_tinysites').val(content.replace(pk, ''));
    },
    addParentTinysites: function (pk) {
        $.ajax({
            'url': '/dashboard/manage_dest/parents/',
            'type': 'GET',
            'dataType': 'json',
            'data':{
                'site_id': pk
            },
            success:function(resp){
                $.each(resp, function(i, val) {
                    page.appendTinysite(val.pk, val.title);
                });
                // for(i in resp) {
                //     var p = resp[i];
                //     page.appendTinysite(p.pk, p.title);
                // }
            }
        });
    },
    tinysiteEvents: function () {
        $('#search-tinysite').click(function(e){
            e.preventDefault();
            var btn = $(this);
            btn.btn('loading');

            $('.options-list').find('li').remove();
            var siteName = $(this).parents('.form-search').find('input').val(),
                btnTemplate = Handlebars.compile($('#btn-template').html());
            $.ajax({
                'url': '/dashboard/manage_dest/search/',
                'type': 'GET',
                'dataType': 'json',
                'data':{
                    'key': siteName,
                    'model': 'all'
                },
                success:function(data){
                    btn.btn('reset');
                    $.fancybox($('.options-ctn'), {
                        width: 400,
                        autoSize: false
                    });
                    $('.options-list').append(btnTemplate(data));
                }
            });
        });

        $(document).on('click', '.option', function(){
            var siteId = $(this).data('site_id');
            var title = $(this).data('site_name');
            page.appendTinysite(siteId, title);
            $.fancybox.close();
        });
    },
    relatedTripEvents: function () {
        $('#search-related-trip').on('click', page.searchRelatedTrip);
        $('#newRelatedTrip').select2({
            placeholder: '--请选择一个游记--',
            minimumInputLength: 1,
            ajax: {
                url: '/dashboard/query/ajax/search_trips/',
                dataType: 'json',
                data: function (term, page) {
                    return {
                        key: term,
                    };
                },
                results: function (data, page) {
                    return {results: data.trips};
                }
            }
        });
    },
    supplierEvents: function () {
        $('#supplierinfo').select2();
    },

    cityHunterEvents: function () {
        $('#cityhunter_sel').select2();
    },

    deleteTrip: function (pk){
        $('#trip-' + pk).remove();
        var ids = $('#id_related_trips').val();
        $('#id_related_trips').val(ids.replace(pk, ''));
    },
    appendRelatedTrip: function (pk, encryptId, title){
        if ($('#trip-' + pk).length) {
            $('#trip-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_related_trips').val().split(',');
            ids.push(pk);
            $('#id_related_trips').val(ids.join(','));

            var html = '<li id="trip-' + pk + '" data-pk="' + pk +
                    '"><a class="name" target="_blank" href="/trips/' +
                    encryptId + '/">' + title +
                    '</a><a class="close" onclick="page.deleteTrip(' + pk +
                    ')">&times;</a></li>';

            $('#related-trips-panel').append(html);
        }
    },
    searchRelatedTrip: function (e){
        e.preventDefault();
        /*
        $.get("/dashboard/query/ajax/trip/", {
            "id": $("#newRelatedTrip").val()
        }, function(data){
            if(data.trip){
                var t = data.trip;
                append_related_trip(t.id, t.encrypt_id, t.name);
                $("#manageRelatedTrip").modal("hide");
            } else {
                alert("未找到改游记")
            }
        }, "json")
        */

        var tripId = $('#newRelatedTrip').val();
        var tripName = $('#manageRelatedTrip .select2-container .select2-chosen').text();
        page.appendRelatedTrip(tripId, null, tripName);
        $('#manageRelatedTrip').modal('hide');
    },
    addSubProduct: function (e){
        e.preventDefault();
        window.open(url.SUB_PRODUCT, page.newWindowFeatures);
    },
    appendSubProduct: function (pk, title){
        if ($('#sub-product-' + pk)[0]) {
            $('#sub-product-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_sub_products').val().split(',');
            ids.push(pk);
            $('#id_sub_products').val(ids.join(','));

            var html = '<li id="sub-product-' +
                       pk + '" data-pk="' + pk +
                       '"><a class="name" target="_blank" href="/dashboard/tp/sub_product/?id=' +
                       pk + '&category='+ CATEGORY +'">' +
                       title + '</a><a class="close" onclick="page.deleteSubProduct(' + pk +
                       ')">&times;</a></li>';
            $('#sub-product-panel').append(html);
        }
    },
    deleteSubProduct: function (pk){
        $('#sub-product-' + pk).remove();
        var ids = $('#id_sub_products').val();
        $('#id_sub_products').val(ids.replace(pk, ''));
    },
    subProductEvents: function () {
        $('#add-sub-product').on('click', page.addSubProduct);
        $('#sub-product-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#sub-product-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                });
                $('#id_sub_products').val(ids.join(','));
            }
        });
        $('#sub-product-panel').disableSelection();
    },
    addSimilarProduct: function (title, id){
        var html = '<div class="alert alert-success" data-id="' +
            id + '"><button type="button" class="close" data-dismiss="alert">&times;</button><a target="_blank" href="/tp/customization/' + id + '/">' +
            title + '</a></div>';
        $('#similarProduct').append($(html));
    },
    selectSimilarProduct: function (){
        var title = $('#similarProductName').val(),
            id = title.split('.')[1],
            input = $('#id_similar_product'),
            value = input.val() || [];
        page.addSimilarProduct(title, id);
        value.push(id);
        input.val(value);
        $('#similarProductName').val('');
    },
    listAllSimilarProduct: function (){
        $('body').css('overflow', 'hidden');
        if ($('#similarProduct .alert-success').length >= 5) {
            alert('已经5个了，不能再多了');
            return;
        }
        setTimeout(function(){
            $('#similarProductName').autocomplete('search', 'No.');
        }, 1500);
    },
    similarPruductEvents: function () {
        $('#add-similar-product').on('click', page.listAllSimilarProduct);
        $('#select-similar-product').on('click', page.selectSimilarProduct);
        var similar = $('#id_similar_product').val() || [];
        for(var i = 0; i < similar.length; i++){
            var p = $('#id_similar_product').find('[value=' + similar[i] + ']');
            page.addSimilarProduct(p.text(), similar[i]);
        }

        // 删除相关旅行产品时的操作
        $('#similarProduct').find('.alert').on('closed', function(){
            var droppedId = $(this).data('id'),
                ids = $('#id_similar_product').val(),
                newIds = [];

            for(var i in ids){
                if(ids[i] == droppedId){
                    continue;
                }
                newIds.push(ids[i]);
            }
            $('#id_similar_product').val(newIds);
        });

        // 自动补全相关旅行产品
        page.names = [];
        $('#id_similar_product option').each(function(){
            var opt = $(this);
            page.names.push('No.' + opt.val() + '. ' + opt.text());
        });

        $('#manageSimilarProduct').on('hide', function(){
            $('body').css('overflow', 'auto');
            $('#similarProductName').autocomplete('close');
        }).on('shown', function(){
            if($('#similarProduct .alert-success').length >= 5){
                $('#manageSimilarProduct').modal('hide');
            }
        });

        $('#similarProductName').autocomplete({
            source: page.names,
            close : function(event, ui){
                $('body').css('overflow', 'auto');
                var name = $('#similarProductName').val();
                if(name.indexOf('No.') > -1) {
                    page.selectSimilarProduct();
                    $('#manageSimilarProduct').modal('hide');
                }
            }

        });
    },
    saveDepartPlace: function (){
        var value = [];
        $('#selectedDepartPlacePanel').html('');
        $('#departPlacePanel li').each(function(){
            var e = $(this);
            if(e.hasClass('selected')){
                value.push(e.text());
                $('#selectedDepartPlacePanel').append(e.clone());
            }
        });
        $('#id_depart_places').val(value.join(','));
        $('#manageDepartPlace').modal('hide');
    },
    departPlaceEvents: function () {
        page.initDepartPlace();
        $('#save-depart-place').on('click', page.saveDepartPlace);
        $('#departPlacePanel').on('click', 'li',function(){
            var e = $(this);
            if (e.hasClass('selected')) {
                e.removeClass('selected');
            } else {
                e.addClass('selected');
            }
        });
        $('#id_depart_places').parents('.controls').find('.error').addClass('hide');
    },
    initDepartPlace: function (){
        var selectedPlaces = $('#id_depart_places').val().split(',');
        $('#departPlacePanel li').each(function(){
            var e = $(this);
            if (page.inArray(e.text(), selectedPlaces)) {
                e.addClass('selected');
                $('#selectedDepartPlacePanel').append(e.clone());
            }
        });
    },
    unpublishedProduct: function (e){
        e.preventDefault();
        if (confirm('确定？')) {
            $.post('', {
                'action': 'unpublish'
            }, function(data){
                if(data.success){
                    window.location.reload();
                } else {
                    alert('删除失败 ' + data.errmsg);
                }
            }, 'json');
        }
    },
    transTp2CityHunter: function (e){
        e.preventDefault();
        if (confirm('确定要将该产品转换成city hunter产品？')) {
            $.post('', {
                'action': 'trans2cityhunter'
            }, function(data){
                if(data.success){
                    window.location.reload();
                } else {
                    alert('删除失败 ' + data.errmsg);
                }
            }, 'json');
        }
    },
    saveMonthCal: function (){
        var months = [];
        $('#cal_month input:checked').each(function(){
            var month = $(this).val();
            months.push(month);
        });
        console.log(months);

        $.post(URL.MONTH_CAL, {
            'data': String(months),
            'product_pk': PRODUCT_PK
        }, function(data){
            console.log(data);
            if(!data.success){
                alert('月历添加失败!');
            }
        }, 'json');
        $('#manageMonth').modal('hide');
    },
    renderMonthCalendar: function (e) {
        e.preventDefault();
        $.get('/dashboard/tp/month_cal/?product_pk='+PRODUCT_PK, {}, function(data){
            var months = data.data.split(',');
            $(months).each(function(index, el) {
                $('#calMonth'+el).prop('checked', true);
            });
        }, 'json');
    },
    monthCalendarEvents: function () {
        $('#manage-month-calendar').one('click', page.renderMonthCalendar);
        $('#save-month-calendar').on('click', page.saveMonthCal);
    },
    seckillEvents: function () {
        $('#id_seckill_start_time').datetimepicker({
            dateFormat: 'yy-mm-dd'
        });
    },
    expiredateEvents: function () {
        $('#id_expire_date').datepicker({
            dateFormat: 'yy-mm-dd'
        });
    },
    virtualProductEvents: function () {
        $('#virtual_code_excel_sample').popover({
            html: true,
            trigger: 'hover',
            content: '<table class=\"table table-bordered\">' + '<tr><td>st1411797445115</td><td>2015-01-19</td></tr>' + '<tr><td>st1411797445116</td><td>2015-01-19</td></tr>' + '<tr><td>st1411797445117</td><td>2015-01-19</td></tr>' + '</table>'
        });

        $('#upload-codes-file').toggle($('#id_is_virtual').is(':checked'));
        $('#upload-codes-file input[type=file]').bootstrapFileInput();
        // and register event
        $('#id_is_virtual').change(function() {
            $('#upload-codes-file').toggle($(this).is(':checked'));
        });
    },
    triggerLanguageInput: function () {
        var checkedInputs = $('#language input:checked'),
            ids = [];
        $.each(checkedInputs, function(i, val) {
            var name = $(val).attr('data-name');
            ids.push(name);
        });
        $('#id_langauges').val(ids.join(','));
    },
    languageEvents: function () {
    // City Hunter 语言
        page.triggerLanguageInput();
        $('#language input').on('change', page.triggerLanguageInput);
    },
    triggerProductTabInput: function () {
        var checkedInputs = $('#prodcut-tab input:checked'),
            ids = [];
        $.each(checkedInputs, function(i, val) {
            var id = $(val).attr('data-id');
            ids.push(id);
        });
        console.log(ids);
        $('#id_product_tabs').val(ids.join(','));
    },
    productTabEvents: function () {
    // City Hunter 属性标签
        page.triggerProductTabInput();
        $('#prodcut-tab input').on('change', page.triggerProductTabInput);
    },
    MapEvents: function (opts) {
        // if (map.size()) {
            var initialize = function () {
                var targetLat = opts.$lat.val(),
                    targetLng = opts.$lng.val(),
                    zoom = 16,
                    initOptions = {
                        zoom: zoom,
                        maxZoom: 18,
                        minZoom: 3,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                opts.map = bt.gmap.createMap(opts.dom, initOptions);

                if ( targetLat ) {
                    bt.gmap.setCenter(opts.map, targetLat, targetLng);
                    page.placeMarker(opts.map, targetLat, targetLng, opts);
                }else{
                    bt.gmap.zoomToChina(opts.map);
                }

                bt.gmap.addListener(opts.map, 'click', function(event) {
                    page.placeMarker(opts.map, event.latLng.lat(), event.latLng.lng(), opts);
                });
            };
            bt.gmap.initMapScript(initialize);
        // }
        var searchMap = function () {
            var address = $('#'+opts.dom).prev('.search').find('input').val();
            page.mapSearchEvents(address, opts);
        };
        $('#'+opts.dom).prev('.search').find('a').on('click', function (e) {
            e.preventDefault();
            searchMap();
        });
        $('#'+opts.dom).prev('.search').find('input').on('keydown', function (e) {
            if(e.keyCode == 13) {
                searchMap();
                return false;
            }
        });
    },
    mapSearchEvents: function (address, opts) {
        if($.trim(address)) {
            bt.gmap.searchAddress(opts.map, address, function(result) {
                var latLng = result[0].geometry.location;
                page.placeMarker(opts.map, latLng.lat(), latLng.lng(), opts);
            });
        }
    },
    placeMarker : function(map, lat, lng, opts) {
        if(google) {
            if (opts.marker) {
                opts.marker.setMap(null);
            }

            opts.marker = bt.gmap.createMarker({
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: bt.gmap.createLatLng(lat, lng),
                map: map,
                zIndex: google.maps.Marker.MAX_ZINDEX
            });

            page.updateMarkerLocation(lat, lng, opts);
            bt.gmap.addListener(opts.marker, 'dragend', function () {
                page.updateMarkerLocation(lat, lng, opts);
            });
        }
    },
    updateMarkerLocation : function (lat, lng, opts) {
        var latLng = opts.marker.getPosition();
        opts.$lat.val(latLng.lat());
        opts.$lng.val(latLng.lng());
    },
    durationEvents: function () {
        var $min = $('#id_duration_min'),
            $max = $('#id_duration_max'),
            triggerMaxValue = function () {
                var value = $(this).val();
                if ($max.data('disable') !== true) {
                    $max.val(value);
                }
            },
            disableTrigger = function () {
                $max.attr('data-disable', true);
            };
        $min.on('keyup', triggerMaxValue);
        $max.on('keyup', disableTrigger);
    },
};

page.init();

